<?
//文件上传类
class ClassUpfile
{
	
	function ClassUpfile($aryfile)
	{
		$this->maxsize=300000;					//文件大小默认300K
		$this->ftype='jpg|gif|png|swf';			//后缀限制
		$this->reportErr=1;						//开启报错	修改为0则屏蔽报错
		$this->name=$aryfile['name'];
		$this->type=$aryfile['type'];
		$this->tmp_name=$aryfile['tmp_name'];
		$this->error=$aryfile['error'];
		$this->size=$aryfile['size'];
		$this->houzhui=$this->getHouzhui();
	}
	
	//取得文件后缀名
	function getHouzhui()
	{
		//文件类型判断
		$aryFileName=explode('.',$this->name);
		if(is_array($aryFileName))
		{
			$len=count($aryFileName);
			if($len<2)
			{
				if($this->reportErr==1)
				{
					echo '文件类型不匹配';
				}
				return false;
			}
			$this->houzhui=$aryFileName[$len-1];		//文件后缀
			return $this->houzhui;
		}
	}
	
	//上传文件检测
	function checkfile($maxsize='',$ftype='')
	{
		if($this->error!='')
		{
			if($this->reportErr==1)
			{
				echo $this->error;
			}
			return false;
		}
		
		if($maxsize!='')
		{
			$this->maxsize=$maxsize;
		}
		if($ftype!='')
		{
			$this->ftype=$ftype;
		}
		
		//文件大小判断
		if($this->size>$this->maxsize)
		{
			if($this->reportErr==1)
			{
				$size=$this->maxsize/1000;
				echo '文件大小超过所限制的'.$size.'K';
			}
			return false;
		}
		
		$aryFiletype=explode('|',$this->ftype);
		if(is_array($aryFiletype))
		{
			foreach($aryFiletype as $key => $value)
			{
				if($value!='')
				{
					if($value==$this->houzhui && $this->houzhui!='')
					{
						return true;
					}
				}
			}
		}

		if($this->reportErr==1)
		{
			echo $this->houzhui.'|文件类型不匹配';
		}
		return false;
	}
	
	//文件上传 path为上传路径
	function upload($path,$filename='')
	{
		if($filename=='')
		{
			$filename=md5(time().rand(1000,9999));
		}
		if($this->checkfile())
		{
			$this->createFolder($path);
			if(move_uploaded_file($this->tmp_name,$path.$filename.'.'.$this->houzhui))
			{
				return $filename.'.'.$this->houzhui;
			}
		}
		else
		{
			return false;
		}
	}
	
	/*
	创建文件夹
	$path 文件路径
	*/
	function createFolder($path) 
	{ 
		
		if (!file_exists($path)) 
		{ 
			if($this->createFolder(dirname($path)))
			{
				if(mkdir($path, 0777))
				{
					return true;
				} 
				else
				{
					return false;
				}
			}
		} 
		else
		{
			return true;
		}
	}
	/** getFileSize 转换文件大小格式
	* @param $size	字节数
	* @return String
	*/
	function getFileSize($size)
	{
		if($size>1000)
		{
			$size=$size/1000;
			$unit='K';
		}
		if($size>1000)
		{
			$size=round($size)/1000;
			$unit='M';
		}
		if($size>1000)
		{
			$size=round($size)/1000;
			$unit='G';
		}
		$ss=$size.' '.$unit;
		return $ss;
	}
}
?>